function initTasksList(){
	$("#tasks_list").jqGrid({
	   	url: CI.baseUrl + '/index.php/tasks_controller/get_json_tasks_list',
		datatype: "json",
		mtype : "post",
	   	colNames:['Id', 'Subject', 'Priority', 'Created Date', 'Status', 'Estimated Hours', 'Worked Hours', 'Completed (%)', 'Action'],
	   	colModel:[
	   		{name:'id', index:'id', width:50},
	   		{name:'subject', index:'subject', width:100},
	   		{name:'priority', index:'priority', width:100},
	   		{name:'creation_date', index:'creation_date', width:100},
	   		{name:'status', index:'status', width:100},
	   		{name:'estimated_hours', index:'estimated_hours', width:150},
	   		{name:'worked_hours', index:'worked_hours', width:150},
	   		{name:'percentaje_completed', index:'percentaje_completed', width:150},
	   		{name:'action', index:'action', width:55, formatter:tasksFormatOperations}
	   	],
	   	rowNum:100,
		height:350,
	   	rowList:[10,20,30],
	   	pager: '#tasks_list_pager',
	   	sortname: 'id',
	    sortorder: "asc",
	    viewrecords: true,
	    caption:"Tasks List"
	});
	jQuery("#tasks_list").jqGrid('navGrid','#tasks_list_pager',{edit:false,add:false,del:false});
}

function autocompleteAssignedTo(){
	$("#assigned_to").autocomplete({
		source: CI.baseUrl + "index.php/users_controller/get_json_users_autocomplete",
		minLength: 0,
		select: function(event, ui){	
			$("#assigned_to_id").val(ui.item.id);			
		}
	});
}

function autocompleteSprints(){
	$("#sprint").autocomplete({
		source: CI.baseUrl + "/index.php/sprint/get_json_sprints_autocomplete",
		minLength: 0,
		select: function(event, ui){	
			$("#sprint_id").val(ui.item.id);			
		}
	});
}

/*
var projectSprints = null;
function autocompleteSprints(){
	$.ajax({
		url: CI.baseUrl + '/index.php/sprint/get_json_sprints_autocomplete',
		type: 'POST',
		dataType: "json",
		success: function(data){
			projectSprints = data;
			autocompleteSprintsCallback(data);
		},
		error: function(data){
			alert('error retrieving project\'s sprints');
		}
	});
}

function autocompleteSprintsCallback(projectSprints){
	$("#sprint").autocomplete({
		source: projectSprints,
		minLength: 0,
		select: function(event, ui){
			$("#sprint").val(ui.item.label);
			$("#sprint_id").val(ui.item.value);
			return false;
		}
	});
}
*/
function tasksFormatOperations(cellvalue, options, rowObject) {
	return 	"<a href='" + CI.baseUrl + "index.php/tasks_controller/detail_view/" + rowObject[0] + "'><img style='margin-right:2px' src=" + CI.baseUrl + "/img/magnifier.png></img></a>" + 
	"<a href='#' onclick=editTask("+ rowObject[0] + ")><img src=" + CI.baseUrl + "/img/edit2.png></img></a>" +
	"<a href='#' onclick=deleteTask(" + rowObject[0] + ")><img src=" + CI.baseUrl + "/img/delete.png></img></a>";
	
}

function deleteTask(id){
	if (confirm("Are you sure?")){
		window.location.href = CI.baseUrl + "index.php/tasks/delete/" + id;
	}
}
function initTaskModal(){
	$("#dialog_form").dialog({
		autoOpen: false,
		height: 600,
		width: 500,
		modal: true,
		buttons: {
			"Save": function(){
				document.forms["form_upsert_task"].submit();
				$(this).dialog("close");
			}
		},
		close: function() {
		}
	});
}
function editTask(taskId){
	$.ajax({
		url: CI.baseUrl + '/index.php/tasks_controller/get',
		type: 'POST',
		data: {'id': taskId},
		dataType: "json",
		success: function(data){
			editTaskDialog(data);
		},
		error: function(data){
			alert('error');
		}
	});
}

function editTaskDialog(taskData){
	$("#subject")			.val(taskData.subject);
	$("#description")		.val(taskData.description);
	$("#priority")			.val(taskData.priority);
	$("#status")			.val(taskData.status);
	$("#completed")			.val(taskData.completed);
	$("#estimated_hours")	.val(taskData.estimated_hours);
	$("#worked_hours")		.val(taskData.worked_hours);
	$("#assigned_to")		.val(taskData.assigned_to);
	$("#assigned_to_id")	.val(taskData.assigned_to_id);
	$("#sprint")			.val(taskData.sprint);
	$("#sprint_id")			.val(taskData.sprint_id);
	
	$( "#dialog_form" ).dialog( "open" );
}

function emptyTaskFields()
{
	$("#subject").val("");
	$("#description").val("");
	$("#priority").val("");
	$("#status").val("");
	$("#completed").val("");
	$("#estimated_hours").val("");
	$("#worked_hours").val("");
}

function initUsersList(){
	$("#users_list").jqGrid({
		   	url:CI.baseUrl + 'index.php/users_controller/get_json_users_list',
		   	editurl: CI.baseUrl + 'index.php/user/edit',
			datatype: "json",
			mtype : "post",
		   	colNames:['Id','Username', 'Name', 'Lastname','Email','Action'],
		   	colModel:[
		   		{name:'id',index:'id', width:100},
		   		{name:'username',index:'username', width:200},
		   		{name:'name',index:'name', width:180},
		   		{name:'last_name',index:'last_name', width:180},
		   		{name:'email',index:'email', width:190},
		   		{name:'action', index:'action', width:40, formatter:usersFormatOperations}
		   	],
		   	rowNum:20,
		   	rowList:[10,20,30],
		   	pager: '#users_list_pager',
		   	sortname: 'id',
		    sortorder: "asc",
		    viewrecords: true,
		    caption:"Users List"
		});
		jQuery("#users_list").jqGrid('navGrid','#users_list_pager',{edit:false,add:false,del:false, search:false, del:false});
		$("#users_list").navButtonAdd('#users_list_pager', {  
			 caption: " ",   
			 title: "Click here to create a user",   
			 buttonicon: "ui-icon-plusthick",   
			 onClickButton: function() { 
				emptyUserFields();
				 $( "#dialog-form" ).dialog( "open" );
			  },   position: "first" })
		.navButtonAdd('#users_list_pager', {  
			 caption: " ",   
			 title: "Edit selected user",   
			 buttonicon: "ui-icon-pencil",   
			 onClickButton: function() { 
			    var selr = jQuery('#users_list').jqGrid('getGridParam','selrow')
				editUser(selr);
			  },   position: "last" })
		.navButtonAdd('#users_list_pager', {  
			 caption: " ",   
			 title: "Delete selected user",   
			 buttonicon: "ui-icon-trash",   
			 onClickButton: function() { 
				 var selr = jQuery('#users_list').jqGrid('getGridParam','selrow');
				 deleteUser(selr);
		     },   position: "last" });
}
function initUserModal(){
	$(function() {
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			show: 'blind',
			hide: 'blind',
			position: 'top',
			modal: true,
			buttons: {
				"Save": function() {
					document.forms["form_upsert_user"].submit();
					$( this ).dialog( "close" );
									},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				
			}
		});

		$( "#create-user" )
			.button()
			.click(function() { 
				emptyUserFields();
				$( "#dialog-form" ).dialog( "open" );
			});
	});			
}

function usersFormatOperations(cellvalue, options, rowObject) {
	return 	"<a href='#' onclick=editUser(" + rowObject[0] + ")><img src=" + CI.baseUrl + "/img/edit2.png></img></a>" +
			"<a href='#' onclick=deleteUser(" + rowObject[0] + ")><img src=" + CI.baseUrl + "/img/delete.png></img></a>";
}
function editUser(idUser){
	$.ajax({
		url: CI.baseUrl + '/index.php/user/get',
		type: 'POST',
		data: {'id': idUser},
		dataType: "json",
		success: function(data){
			editUserDialog(data);
		},
		error: function(data){
			alert('error');
		}
	});
}
function editUserDialog(userData){
    $("#id").val(userData.id);
 	$("#firstname").val(userData.firstname);
	$("#lastname").val(userData.lastname);
	$("#address").val(userData.address);
	$("#tel").val(userData.tel);
	$("#email").val(userData.email);
	$("#country").val(userData.country);
	$("#language").val(userData.language);
	$("#username").val(userData.username);
	$("#password").val(userData.password);
	$( "#dialog-form" ).dialog( "open" );
}

function emptyUserFields()
{
	$("#firstname").val("");
	$("#lastname").val("");
	$("#address").val("");
	$("#phone").val("");
	$("#email").val("");
	$("#country").val("");
	$("#lan").val("");
	$("#username").val("");
	$("#password").val("");

}

function deleteUser(idUser){
	if (confirm("Are you sure?")){
		var myForm = document.createElement("form");
		myForm.method="post" ;
		myForm.action = CI.baseUrl + "index.php/user/delete";
		var myInput = document.createElement("input") ;
		myInput.setAttribute("name", "idUser") ;
		myInput.setAttribute("type", "hidden");
		myInput.setAttribute("value", idUser);
		myForm.appendChild(myInput);
		document.body.appendChild(myForm) ;
		myForm.submit() ;
	}	
}

function loadUserProjects(){
	$.ajax({
		url: CI.baseUrl + '/index.php/project_controller/get_user_projects',
		type: 'POST',
		dataType: "json",
		success: function(data){
			loadUserProjectsCallback(data);
		},
		error: function(data){
			alert('projects select error');
		}
	});
}

function loadUserProjectsCallback(data){
	$(document.createElement('select'))
	.attr({
		id: 'user_projects_select',
		name: 'user_projects_select',
		onChange: 'javascript:setCurrentProject();'
	})
	.appendTo("#user_projects_container");
	
	for(var i=0; i<data.length; i++){
		$(document.createElement('option'))
		.attr({
			value: data[i].id,
			selected: data[i].selected
		})
		.text(data[i].name)
		.appendTo("#user_projects_select");
	}
}

function setCurrentProject(){
	var projectId = $("#user_projects_select").val();
	
	$.ajax({
		url: CI.baseUrl + '/index.php/authentication_controller/set_current_project',
		type: 'POST',
		data: {'current_project': projectId},
		dataType: "json",
		success: function(data){
			window.location.reload();
		},
		error: function(data){
			alert('unable to set current project');
		}
	});
}